package dao

import (
	"2-11zy/inits"
	"2-11zy/models"
)

func AddRoom(userId int) models.Room {
	room := models.Room{
		RoomUserId: userId,
	}

	err := inits.DB.Debug().Create(&room).Error
	if err != nil {
		return models.Room{}
	}
	userRoom := models.UserRoom{
		RoomUserId: userId,
		ULevel:     1,
		Room_id:    int(room.ID),
	}
	err = inits.DB.Debug().Create(&userRoom).Error
	if err != nil {
		return models.Room{}
	}
	return room

}

func IsExitsUserIds(ids []int) bool {
	for _, userid := range ids {
		var user = models.User{}
		if err := inits.DB.Debug().Where("id = ?", userid).Find(&user).Error; err != nil {
			return false
		}
		if user.ID == 0 {
			return false
		}
	}
	return true
}

func IsExitsRoomByRoomId(roomId int) bool {
	room := models.Room{}
	if int(room.ID) == roomId {
		return false
	}
	return true
}

func GetRoomByRoomId(roomId int, roomUserId int) models.UserRoom {
	var room models.UserRoom
	err := inits.DB.Debug().Where("room_id = ?", roomId).Where("room_user_id = ?", roomUserId).Find(&room).Error
	if err != nil {
		return models.UserRoom{}
	}
	return room
}

func CreateRoomUser(ids []int, roomId int) bool {
	for _, userId := range ids {
		id := GetRoomByRoomId(roomId, userId)
		if id.ID != 0 {
			continue
		}
		err := inits.DB.Create(&models.UserRoom{
			RoomUserId: userId,
			Room_id:    roomId,
		}).Error
		if err != nil {
			return false
		}
	}
	return true
}
